#include "string.h"


String::String(const char *str){
	if(str){
		//str不为空
		length = std::strlen(str);
		data = new char(length + 1);
		std::strcpy(data, str);
	}
}

String::String(const String& rhs) : length(rhs.length){
	data = new char(length + 1);
	std::strcpy(data, rhs.data);
}

String& String::operator=(const String& rhs){
	if(this != &rhs){
		length = rhs.length;
		delete[] data;
		data = new char(length + 1);
		std::strcpy(data, rhs.data);
	}
	return *this;
}
String::String(String&& rhs)noexcept : data(rhs.data) ,length(rhs.length){
	rhs.length = 0;
	rhs.data = nullptr;
}
//对于移动赋值而言，在移动后rhs还保存着对其资源的控制权吗？
String& String::operator=(String&& rhs) noexcept{
	if(this != &rhs){
		delete[] data;
		data = rhs.data;
		length = rhs.length;
		rhs.length = 0;
		rhs.data = nullptr;
	}
	return *this;
}

String& String::operator+=(const String& rhs){
	length += rhs.length;
	char *temp = new char(length + 1);
	std::strcpy(temp, data);
	std::strcat(temp, rhs.data);
	delete[] data;
	data = temp;
	delete[] temp;
	return *this;
}
std::ostream& operator<<(std::ostream& os, const String& str) {
	for (size_t i = 0; i < str.getLength(); ++i) {
		os << str[i];
	}
	return os;
}

// 使用迭代器插入字符
StringIterator String::insert(StringIterator pos, char ch) {
	size_t index = pos.getPtr() - data;
	char* newData = new char[length + 1];
	std::memcpy(newData, data, index);
	newData[index] = ch;
	std::memcpy(newData + index + 1, data + index, length - index);
	delete[] data;
	data = newData;
	++length;
	return StringIterator(data + index);
}

// 新增接受索引值的 insert 重载版本
StringIterator String::insert(size_t index, char ch) {
	if (index > length) {
		// 处理索引越界情况，这里简单返回 end 迭代器
		return end();
	}
	StringIterator pos = begin();
	for (size_t i = 0; i < index; ++i) {
		++pos;
	}
	return insert(pos, ch);
}
